import Vue from 'vue'
import axios from 'axios'
import qs from 'qs'
import { Toast } from 'mint-ui'

/* eslint-disable eol-last */
axios.defaults.baseURL = process.env.API_HOST // 开发环境中反向代理解决跨域问题，实际环境中 baseUrl 为空

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
  const data = response.data

  return data

  // if (data.response === 'success') {
  //   return data.data
  // } else {
  //   Toast(data.data.msg)
  //   return Promise.reject(data.data.msg)
  // }
}, (err) => {
  if (err && err.response) {
    switch (err.response.status) {
      case 400:
        err.message = '请求错误'
        break
      case 401:
        err.message = '未授权，请登录'
        break
      case 403:
        err.message = '拒绝访问'
        break
      case 404:
        err.message = `请求地址出错: ${err.response.config.url}`
        break
      case 408:
        err.message = '请求超时'
        break
      case 500:
        err.message = '服务器内部错误'
        break
      case 501:
        err.message = '服务未实现'
        break
      case 502:
        err.message = '网关错误'
        break
      case 503:
        err.message = '服务不可用'
        break
      case 504:
        err.message = '网关超时'
        break
      case 505:
        err.message = 'HTTP版本不受支持'
        break
      default:
    }
    Toast(err.response.status + ': ' + err.message)
  }

  return Promise.reject(err)
})

export function simplePost (url, param) {
  return new Promise(function (resolve, reject) {
    axios({
      method: 'post',
      url: url,
      headers: {'Content-type': 'application/x-www-form-urlencoded'},
      data: qs.stringify(param)
    }).then(data => {
      if (data.response === 'success') {
        resolve(data.data)
      } else {
        Toast(data.data.msg)
        reject(data.data.msg)
      }
    }).catch((err) => {
      reject(err)
    })
  })
}

export function complexPost (url, param) {
  return new Promise(function (resolve, reject) {
    axios({
      method: 'post',
      url: url,
      data: param
    }).then(data => {
      if (data.response === 'success') {
        resolve(data.data)
      } else {
        Toast(data.data.msg)
        reject(data.data.msg)
      }
    }).catch((err) => {
      reject(err)
    })
  })
}

export function uploadFile (file, url) {
  debugger
  let formData = new FormData()
  formData.append('multipartFile', file)

  return new Promise(function (resolve, reject) {
    axios({
      method: 'post',
      url: url,
      headers: {'Content-type': 'multipart/form-data'},
      data: formData
    }).then(data => {
      if (data.response === 'success') {
        resolve(data.data)
      } else {
        Toast(data.data.msg)
        reject(data.data.msg)
      }
    }).catch((err) => {
      reject(err)
    })
  })
}

Vue.prototype.$http = axios
Vue.prototype.$http.simplePost = simplePost
Vue.prototype.$http.complexPost = complexPost
Vue.prototype.$http.uploadFile = uploadFile
